<template>
  <!-- 搜索 -->
  <ContentWrap>
    <el-form ref="queryFormRef" :model="queryParams" class="-mb-15px">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="寄存门店" prop="tenantIds">
            <el-select v-model="queryParams.tenantIds" clearable multiple placeholder="全部">
              <el-option
                v-for="item in tenantList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="寄存员工" prop="employeeName">
            <el-select v-model="queryParams.employeeName" clearable placeholder="全部">
              <el-option
                v-for="item in employeeList"
                :key="item.employeeId"
                :label="item.employeeName"
                :value="item.employeeId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              :shortcuts="defaultShortcuts"
              :disabled-date="disabledDate"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              end-placeholder="自定义时间"
              start-placeholder="自定义时间"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="聚合搜索">
            <el-input
              v-show="true"
              v-model="queryParams[queryType.queryParam]"
              clearable
              placeholder="请输入"
              :type="queryType.queryParam === 'userId' ? 'number' : 'text'"
            >
              <template #prepend>
                <el-select
                  v-model="queryType.queryParam"
                  class="!w-100px"
                  placeholder="全部"
                  @change="inputChangeSelect"
                >
                  <el-option
                    v-for="dict in dynamicSearchList"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon class="mr-5px" icon="ep:search" />
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon class="mr-5px" icon="ep:refresh" />
              重置
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>
  <!-- 统计卡片 -->
  <el-row :gutter="10">
    <el-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="寄存订单数量"
        class="mb-10px"
        icon="icon-park-outline:transaction-order"
        icon-color="bg-blue-100"
        icon-bg-color="text-blue-500"
        :value="summary?.orderCount || 0"
      />
    </el-col>
    <el-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="寄存商品数量"
        class="mb-10px"
        icon="ri:refund-2-line"
        icon-color="bg-green-100"
        icon-bg-color="text-green-500"
        :value="summary?.productCount || 0"
      />
    </el-col>
    <el-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="寄存商品会员"
        class="mb-10px"
        icon="icon-park-outline:transaction-order"
        icon-color="bg-blue-100"
        icon-bg-color="text-blue-500"
        :value="summary?.orderUser || 0"
      />
    </el-col>
    <el-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="寄存商品价值"
        class="mb-10px"
        icon="ri:refund-2-line"
        icon-color="bg-green-100"
        icon-bg-color="text-green-500"
        prefix="￥"
        :decimals="2"
        :value="Number(fenToYuan(summary?.orderTotalPrice || 0))"
      />
    </el-col>
  </el-row>
  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      row-key="id"
      :cell-style="{ padding: 0, borderBottom: 'none' }"
      :header-cell-style="{ padding: 0 }"
      :row-class-name="'table-row-class'"
    >
      <OrderTableColumn :list="list">
        <template #default="{ row }">
          <div class="flex items-center justify-center">
            <!-- <el-button v-hasPermi="['trade:order:query']" link type="primary">
              <Icon icon="ep:notification" />
              提货
            </el-button> -->
            <el-dropdown
              v-hasPermi="['trade:order:update']"
              @command="(command) => handleCommand(command, row)"
            >
              <el-button link type="primary">
                <Icon icon="ep:d-arrow-right" />
                更多
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="cancel">
                    <Icon icon="ep:chat-line-square" />
                    撤销订单
                  </el-dropdown-item>
                  <!-- <el-dropdown-item command="">
                    <Icon icon="ep:chat-line-square" />
                    打印小票
                  </el-dropdown-item> -->
                  <el-dropdown-item command="logs">
                    <Icon icon="ep:chat-line-square" />
                    订单日志
                  </el-dropdown-item>
                  <el-dropdown-item command="remark">
                    <Icon icon="ep:chat-line-square" />
                    订单备注
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </OrderTableColumn>
      <template #empty>
        <Empty />
      </template>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 各种操作的弹窗 -->
  <OrderPickUpForm ref="pickUpForm" @success="getList" />
  <OrderUpdateRemarkForm ref="updateRemarkForm" @success="getList" />
  <OrderCancelRemarkForm ref="cancelRemarkFormRef" @success="getList" />
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import * as TradeOrderApi from '@/api/mall/trade/order'
import { TradeOrderSummaryRespVO } from '@/api/mall/trade/order'
import OrderPickUpForm from '@/views/mall/trade/order/form/OrderPickUpForm.vue'
import OrderUpdateRemarkForm from '@/views/mall/trade/order/form/OrderUpdateRemarkForm.vue'
import OrderCancelRemarkForm from '@/views/mall/trade/order/form/OrderCancelRemarkForm.vue' //订单撤销

import { OrderTableColumn } from './components'
import { fenToYuan } from '@/utils'
import { defaultShortcuts } from '@/utils/formatTime'
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}
defineOptions({ name: 'DepositOrder' })

// 列表的加载中
const loading = ref(true)
// 列表的总页数
const total = ref(2)
// 列表的数据
const list = ref<TradeOrderApi.OrderVO[]>([])
// 搜索的表单
const queryFormRef = ref<FormInstance>()
// 初始表单参数
const INIT_QUERY_PARAMS = {
  // 页数
  pageNo: 1,
  // 每页显示数量
  pageSize: 10,
  // 创建时间
  createTime: undefined,
  typeClass: 3,
  tenantIds: undefined, //服务门店
  employeeName: undefined //销售员工
}
// 表单搜索
const queryParams = ref({ ...INIT_QUERY_PARAMS })
// 订单搜索类型 queryParam
const queryType = reactive({ queryParam: 'no' })
// 订单统计数据
const summary = ref<TradeOrderSummaryRespVO>()

// 订单聚合搜索 select 类型配置（动态搜索）
const dynamicSearchList = ref([
  { value: 'no', label: '订单号' },
  { value: 'userId', label: '用户UID' },
  { value: 'userNickname', label: '姓名昵称' },
  { value: 'userMobile', label: '用户电话' }
])
/**
 * 聚合搜索切换查询对象时触发
 * @param val
 */
const inputChangeSelect = (val: string) => {
  dynamicSearchList.value
    .filter((item) => item.value !== val)
    ?.forEach((item) => {
      // 清除集合搜索无用属性
      if (queryParams.value.hasOwnProperty(item.value)) {
        delete queryParams.value[item.value]
      }
    })
}
// 销售门店或商城 选择列表
import * as TenantApi from '@/api/system/tenant'
const tenantList = ref<any>([])
const handleSourceChange = async () => {
  tenantList.value = []
  let params = {
    tenantType: 4
  }
  const data = await TenantApi.getChildTenantWithPostList(params)

  data.map((ele) => {
    tenantList.value.push({
      name: ele.name,
      id: ele.id
    })
  })
}
// 销售员工选择列表
import * as UserApi from '@/api/shop/system/user/index'

const employeeList = ref<any>([])
const getEmployeeList = async () => {
  const data = await UserApi.getEmployeeList()
  employeeList.value = data
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 统计
    summary.value = await TradeOrderApi.getOrderSummary(unref(queryParams))
    // 分页
    const data = await TradeOrderApi.getOrderPage(unref(queryParams))
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  queryParams.value.pageNo = 1
  await getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.value = { ...INIT_QUERY_PARAMS }
  handleQuery()
}

/** 操作分发 */
const updateRemarkForm = ref()
const cancelRemarkFormRef = ref()

const handleCommand = (command: string, row: TradeOrderApi.OrderVO) => {
  switch (command) {
    case 'logs':
      break
    case 'remark':
      updateRemarkForm.value?.open(row)
      break
    case 'cancel':
      cancelRemarkFormRef.value?.open(row)
      break
  }
}
/** 初始化 **/
onMounted(() => {
  handleSourceChange()
  getEmployeeList()
  getList()
})
</script>
<style lang="scss" scoped>
:deep(.order-table-col > .cell) {
  padding: 0;
}

.summary {
  .el-col {
    margin-bottom: 1rem;
  }
}
</style>
